package com.developer.platform.domain.service;

import com.developer.platform.domain.security.AuthenticationInfo;
import com.developer.platform.domain.security.UserDetails;
import java.util.Objects;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;

/**
 * @author ：qiaoliang
 * @date ：2020-11-09
 */
public interface ISecurityService {

    default Authentication getAuthentication(){
        return SecurityContextHolder.getContext().getAuthentication();
    }

    default UserDetails getUserDetails(){
        if(Objects.isNull(getAuthentication())){
            return new UserDetails();
        }
        Object principal = getAuthentication().getPrincipal();
        if("anonymousUser".equals(principal)){
            return new UserDetails();
        }
        return (UserDetails)principal;
    }

    default Long getUserDetailsUserId(){
        UserDetails userDetails = getUserDetails();
        return Objects.nonNull(userDetails)?userDetails.getId():null;
    }

    default void setUserDetails(AuthenticationInfo authenticationInfo){
        SecurityContextHolder.getContext().setAuthentication(authenticationInfo);
    }

    default void clearContext(){
        SecurityContextHolder.clearContext();
    }

}
